/*
 * Copyright 2008 FBK (http://www.fbk.eu/)
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.fbk.it.hlt.jlsi.data;

import java.io.File;
import java.io.IOException;
import java.io.RandomAccessFile;

/**
 * Writes in Sparse Binary Matrix File.
 * 
 * @author Claudio Giuliano
 * @version %I%, %G%
 * @since 1.0
 */
public class SparseBinaryMatrixWriter {
	//
	private RandomAccessFile raf;

	/**
	 * Constructs a sparse binary matrix writer.
	 * 
	 * @param file
	 *            the file where to write the matrix.
	 */
	public SparseBinaryMatrixWriter(File f) throws IOException {
		raf = new RandomAccessFile(f, "rw");

		// a place holder
		writeHeader(0, 0, 0);

	} // end constructor

	/**
	 * Writes the number of rows, columns and non zero values. All values are
	 * 4-byte integers
	 * 
	 * @param nr
	 *            the number of rows.
	 * @param nc
	 *            the number of columns.
	 * @param nz
	 *            the total number of non zero values.
	 */
	public void writeHeader(int nr, int nc, int nz) throws IOException {
		raf.seek(0);

		// write the number of rows
		raf.writeInt(nr);

		// write the number of columns
		raf.writeInt(nc);

		// write the total number of non zero values
		raf.writeInt(nz);

	} // end writeHeader

	/**
	 * write the number of non zero values for a column and or each non-zero
	 * value in the column: row index and value. All values are 4-byte integers
	 * except value, which is a 4-byte float. All are in network byte order.
	 * 
	 * @param nr
	 *            the number of rows.
	 * @param nc
	 *            the number of columns.
	 * @param nz
	 *            the total number of non zero values.
	 */
	public void writeColumn(int[] indexes, float[] values) throws IOException {
		raf.seek(raf.length());

		// write the number of non zero values
		raf.writeInt(indexes.length);

		for (int i = 0; i < indexes.length; i++) {
			// write the row index
			raf.writeInt(indexes[i]);

			// write the value
			raf.writeFloat(values[i]);
		} // end for i

	} // end writeColumn

} // end SparseBinaryMatrixWriter